package pri.zxx.compute;

import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author xigua
 * @desc 公式计算工具
 * @createTime 2022/4/15 11:26
 */
public class ComputeUtil implements ICompute {

    @Override
    public BigDecimal parseAndCompute(EquationBean equationBean, DataBean dataBean) {

        String vitamin = equationBean.getVitamin();


        ExpressionParser expressionParser = new SpelExpressionParser();
        //组装参数上下文
        EvaluationContext context = new StandardEvaluationContext();
        context.setVariable("dataBean", dataBean);

        Expression expression = expressionParser.parseExpression(vitamin);
        String value = expression.getValue(context, String.class);
        System.out.println(value);
        return null;
    }

    public static void main(String[] args) {
        EquationBean equationBean = new EquationBean();
        DataBean dataBean = new DataBean();
        ExpressionParser expressionParser = new SpelExpressionParser();
        //组装参数上下文
        EvaluationContext context = new StandardEvaluationContext();
        context.setVariable(DataBean.class.getSimpleName(), dataBean);
        String vitamin = equationBean.getVitamin();
        String regx = "#(.+?)(?=)#";
        Pattern compile = Pattern.compile(regx);
        Matcher matcher = compile.matcher(vitamin);
        List<String> elList = new ArrayList<>();
        while (matcher.find()) {
            elList.add(matcher.group());
        }

        String nowVitamin = vitamin;
        Expression expression;
        String value;
        for (String s : elList) {
            expression = expressionParser.parseExpression(s.substring(0, s.length() - 1));
            value = expression.getValue(context, String.class);
            nowVitamin = nowVitamin.replace(s, value);
        }

        System.out.println(nowVitamin);
    }
}
